//
//  PictureSelectViewController.swift
//  01sinablog
//
//  Created by ZhangZiang on 15/12/25.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let margin : CGFloat = 5
private let columnCount : CGFloat = 5
private let maxImageCount = 9

class PictureSelectViewController: UICollectionViewController {

    var imageList = [UIImage]()
    
    init() {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
        let itemW = (ScreenW - (columnCount + 1)*margin)/columnCount
        
        layout.itemSize = CGSize(width: itemW, height: itemW)
        
        //设置组间距
        layout.sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
        
        super.init(collectionViewLayout: layout)
        
        collectionView?.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        //加1则有添加图片的按钮
        return imageList.count == maxImageCount ? imageList.count : imageList.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectCell
    
        // Configure the cell
        if indexPath.item == imageList.count {
            cell.imageForCell = nil
        } else {
        cell.imageForCell = imageList[indexPath.item]
        }
        cell.delegate = self
    
        return cell
    }

}
//MARK : cell的代理方法(点击),图片选择器的代理方法

extension PictureSelectViewController : PictureSelectCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    func userWillAddIcon(cell: PictureSelectCell) {
        print(__FUNCTION__)
        //如果已经有图片就返回
        if cell.imageForCell != nil {
            return
        }
        
        let picker = UIImagePickerController()
        
        presentViewController(picker, animated: true, completion: nil)
        
        picker.delegate = self
    }
    
    func userWillDeleteIcon(cell: PictureSelectCell) {
        print(__FUNCTION__)
        
        if let index = collectionView?.indexPathForCell(cell) {
            
        imageList.removeAtIndex(index.item)
            
        collectionView?.reloadData()
        }
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK : 自定义的cell

@objc protocol PictureSelectCellDelegate : NSObjectProtocol {
    
    optional func userWillAddIcon(cell : PictureSelectCell)
    
    optional func userWillDeleteIcon(cell : PictureSelectCell)
    
}

class PictureSelectCell: UICollectionViewCell {
    
    var imageForCell : UIImage? {
        didSet {
            //.ScaleAspectFit会使图片边上留白,一般用fill
            iconBtn.imageView?.contentMode = .ScaleAspectFill
            
            
            deleteBtn.hidden = imageForCell == nil
            iconBtn.setImage(imageForCell, forState: .Normal)
            
        }
    }
    
    weak var delegate : PictureSelectCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func addIconBtnDidClicked() {
        delegate?.userWillAddIcon?(self)
    }
    
    @objc private func deleteIconBtnClicked() {
        delegate?.userWillDeleteIcon?(self)
    }
    
    private func setupUI() {
        contentView.addSubview(iconBtn)
        contentView.addSubview(deleteBtn)
        
        iconBtn.snp_makeConstraints { (make) -> Void in
//            make.left.top.right.equalTo(contentView)
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        
        iconBtn.addTarget(self, action: "addIconBtnDidClicked", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteIconBtnClicked", forControlEvents: .TouchUpInside)
    }
    
    lazy var iconBtn = UIButton(imageName: nil, backImageName: "compose_pic_add")
    lazy var deleteBtn = UIButton(imageName: nil, backImageName: "compose_photo_close")
}
